//
//  MainViewController.m
//  ShouYi
//
//  Created by yurui on 16/2/18.
//  Copyright © 2016年 yurui. All rights reserved.
//

#import "MainViewController.h"
#import "ContentTableViewCell.h"
// 轮播图 头文件
#import "DCPicScrollView.h"
#import "DCWebImageManager.h"
//Model
#import "HdListModel.h"
#import "TaskListModel.h"

#import "RenWuHeaderView.h"

@interface MainViewController () <UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong) RenWuHeaderView *headerView;
@property(nonatomic,strong) UIScrollView *scrollView;
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSString *dataType;
//幻灯片
@property(nonatomic,strong) NSMutableArray *hdlistArray;
//本地
@property(nonatomic,strong) NSMutableArray *bendiListArray;
//全国
@property(nonatomic,strong) NSMutableArray *taskListArray;


@end

@implementation MainViewController


- (void)viewWillAppear:(BOOL)animated {
    
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    //重置数据类型
    self.dataType = @"全国";
    [self addHeaderView];
    
    //任务列表
    [self setUpDataForTaskListUrl:KMainUrl];
    
    // 配置tableView
    [self configerTableView];
    
    //轮播图数据
    [self setUpDataForHdlist];

    //添加上拉刷新加载
    [self AddMJrefresh];
}
#pragma mark --- 添加界面 ---
- (void)addHeaderView{
    self.headerView = [[RenWuHeaderView alloc]initWithFrame:CGRectMake(0, 0,kWidth , 64)];
    self.headerView.backgroundColor = kBackGroundColor;
    [self.view addSubview:_headerView];
    // 搜索按钮
    [self.headerView.searchBt addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    // 全国
    [self.headerView.countryBt addTarget:self action:@selector(countryData) forControlEvents:UIControlEventTouchUpInside];
    //本地
    [self.headerView.benDiBt addTarget:self action:@selector(benDiData) forControlEvents:UIControlEventTouchUpInside];
    // 信息
    [self.headerView.messageBt addTarget:self action:@selector(messageAction) forControlEvents:UIControlEventTouchUpInside];
}
// 轮播图  第三方
- (void)configerScrollerView{
    
    NSMutableArray *UrlStringArray = [NSMutableArray array];
    
    for (int i = 0; i < self.hdlistArray.count; i++) {
        HdListModel *model = self.hdlistArray[i];
        [UrlStringArray addObject:model.picurl];
    }
    
    NSArray *titleArray = [@"" componentsSeparatedByString:@"."];
    //显示顺序和数组顺序一致
    //设置图片url数组,和滚动视图位置
    DCPicScrollView  *picView = [DCPicScrollView picScrollViewWithFrame:CGRectMake(0, 64, self.view.frame.size.width,kHeight / 4) WithImageUrls:UrlStringArray];
    //显示顺序和数组顺序一致
    //设置标题显示文本数组
    picView.titleData = titleArray;
    // 占位图
    picView.placeImage = [UIImage imageNamed:@""];
    //图片被点击事件,当前第几张图片被点击了,和数组顺序一致
    [picView setImageViewDidTapAtIndex:^(NSInteger index) {
        
        if (self.taskListArray.count > 0) {
            self.hidesBottomBarWhenPushed = YES;
            TaskListModel *model = self.taskListArray[index];
            DetailViewController *detailVC = [[DetailViewController alloc] init];
            detailVC.webUrl = model.gourl;
            detailVC.imagesrc = model.imgsrc;
            detailVC.title = model.title;
            detailVC.type = @"detail";
            [self.navigationController pushViewController:detailVC animated:YES];
            self.hidesBottomBarWhenPushed = NO;
        }
        
        NSLog(@"点击了第%zd张图",index);
    }];
    //default is 2.0f,如果小于0.5不自动播放
    picView.AutoScrollDelay = 2.0f;
  //  [self.view addSubview:picView];
    
    self.tableView.tableHeaderView = picView;
    //下载失败重复下载次数,默认不重复,
    [[DCWebImageManager shareManager] setDownloadImageRepeatCount:1];
    //图片下载失败会调用该block(如果设置了重复下载次数,则会在重复下载完后,假如还没下载成功,就会调用该block)
    //error错误信息
    //url下载失败的imageurl
    [[DCWebImageManager shareManager] setDownLoadImageError:^(NSError *error, NSString *url) {
        NSLog(@"%@",error);
    }];
}

// 配置TableView
- (void)configerTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kWidth , kHeight - 64 - 44)];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;
    [self.tableView registerClass:[ContentTableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];

}

// 搜索按钮事件
- (void)searchAction{
    
    self.hidesBottomBarWhenPushed = YES;
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
// 全国按钮事件
- (void)countryData{
    self.headerView.imageV.image = [UIImage imageNamed:@"icon_qg.png"];
    self.dataType = @"全国";
    
    if (self.taskListArray.count > 0) {
        
    }else {
        [self setUpDataForTaskListUrl:KMainUrl];
    }
    
    [self.tableView reloadData];
}
// 本地按钮事件
- (void)benDiData{
    self.headerView.imageV.image = [UIImage imageNamed:@"icon_qg_1.png"];
    self.dataType = @"本地";
    if (self.bendiListArray.count > 0) {
        
    }else {
        [self setUpDataForTaskListUrl:KMainUrl];
    }
    [self.tableView reloadData];
}
// 信息按钮事件
- (void)messageAction{
    self.hidesBottomBarWhenPushed = YES;
    MessageViewController *searchVC = [[MessageViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark --- 数据处理 ---
//解析幻灯片
- (void)setUpDataForHdlist {
    
    [LORequestManger GET:KHdlist success:^(id response) {
        
        NSArray *array = (NSArray *)response;
        
        for (NSDictionary *dic in array) {
            
            HdListModel *model = [HdListModel setUpdateDic:dic];
            
            [self.hdlistArray addObject:model];
        }
        [self configerScrollerView];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

//任务刷新 上拉刷新
- (void)setUpDataForTaskListSHANGLAUrl:(NSString *)url{
    
    //刷新数据
    [SVProgressHUD show];
    
     NSString *strIP = [[NSUserDefaults standardUserDefaults] objectForKey:@"IP"];
    
    //判断是本地数据还是全国数据
    if ([self.dataType isEqualToString:@"全国"]) {
        url =[url stringByAppendingString:@"&localtype=0"];
    }else {
        url = [url stringByAppendingString:[NSString stringWithFormat:@"&localtype=1&userip=%@",strIP]];
        NSLog(@"%@",url);
    }

    [LORequestManger GET:url success:^(id response) {
    
        //临时数据存储刷新出来的数据
        NSMutableArray *tempArray = [NSMutableArray array];
        NSArray *array = (NSArray *)response;
        //赋值刷新出来的数据
        for (NSDictionary *dic in array) {
            TaskListModel *model = [TaskListModel setUpDic:dic];
            [tempArray addObject:model];
        }
        //将原数组中的数据添加到临时数组中(判断全国,本地)
        
        if ([self.dataType isEqualToString:@"全国"]) {
            //全国
            for (TaskListModel *TModel in self.taskListArray) {
                [tempArray addObject:TModel];
            }
            //清空原数组,并把临时数组替换原数组
            [self.taskListArray removeAllObjects];
            for (TaskListModel *tempModel in tempArray) {
                [self.taskListArray addObject:tempModel];
            }
        }else {
            //本地
            for (TaskListModel *TModel in self.bendiListArray) {
                [tempArray addObject:TModel];
            }
            //清空原数组,并把临时数组替换原数组
            [self.bendiListArray removeAllObjects];
            for (TaskListModel *tempModel in tempArray) {
                [self.bendiListArray addObject:tempModel];
            }
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        
        [SVProgressHUD dismiss];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
         [self.tableView.mj_header endRefreshing];
        [SVProgressHUD dismiss];

    }];
}
//解析任务列表 下拉加载
- (void)setUpDataForTaskListUrl:(NSString *)url{
    
    [SVProgressHUD show];
    
    
    NSString *strIP = [[NSUserDefaults standardUserDefaults] objectForKey:@"IP"];
    
    //判断是本地数据还是全国数据
    if ([self.dataType isEqualToString:@"全国"]) {
       url =[url stringByAppendingString:@"&localtype=0"];
    }else {
        url = [url stringByAppendingString:[NSString stringWithFormat:@"&localtype=1&userip=%@",strIP]];
       
    }
    [LORequestManger GET:url success:^(id response) {
        
        NSArray *array = (NSArray *)response;
        for (NSDictionary *dic in array) {
            TaskListModel *model = [TaskListModel setUpDic:dic];
            if ([self.dataType isEqualToString:@"本地"]) {
                [self.bendiListArray addObject:model];
                
            }else {
                [self.taskListArray addObject:model];
            }
        }
        
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
        [self.tableView.mj_footer endRefreshing];
        [SVProgressHUD dismiss];
        [self showAlertMessage:@"没有更多数据"];
    }];
}

//添加上拉刷新下拉加载
//刷新 下拉加载
- (void)AddMJrefresh {
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"下拉加载");
        TaskListModel *model = [[TaskListModel alloc] init];
        if ([self.dataType isEqualToString:@"全国"]) {
            model = self.taskListArray.lastObject;
        }else {
            model = self.bendiListArray.lastObject;
        }
        NSString *url = [KTaskList stringByAppendingString:[NSString stringWithFormat:@"&cid=1&preid=%@",model.ID]];
        [self setUpDataForTaskListUrl:url];
    
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"上拉刷新");
        TaskListModel *model = [[TaskListModel alloc] init];
        if ([self.dataType isEqualToString:@"全国"]) {
            model = self.taskListArray.firstObject;
        }else {
            model = self.bendiListArray.firstObject;
        }
        NSString *url = [KTaskList stringByAppendingString:[NSString stringWithFormat:@"&cid=1&nextid=%@",model.ID]];
        [self setUpDataForTaskListSHANGLAUrl:url];
    }];
}

//幻灯片
- (NSMutableArray *)hdlistArray {
    
    if (!_hdlistArray) {
        _hdlistArray = [NSMutableArray array];
    }
    return _hdlistArray;
}
//任务列表(全国)
- (NSMutableArray *)taskListArray {
    if (!_taskListArray) {
        _taskListArray = [NSMutableArray array];
    }
    return _taskListArray;
}
//任务刷新(本地)
- (NSMutableArray *)bendiListArray {
    if (!_bendiListArray) {
        _bendiListArray = [NSMutableArray array];
    }
    return _bendiListArray;
}


#pragma  mark UITableViewDelegate 和UITableViewDataSource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([self.dataType isEqualToString:@"全国"]) {
        return self.taskListArray.count;
    }else {
        return self.bendiListArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    TaskListModel *model = [[TaskListModel alloc] init];
    
    if ([self.dataType isEqualToString:@"全国"]) {
        model = self.taskListArray[indexPath.row];
    }else {
        model = self.bendiListArray[indexPath.row];
    }
    
    [cell setModelForTaskList:model];

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.hidesBottomBarWhenPushed = YES;
    TaskListModel *model = self.taskListArray[indexPath.row];
    
    
    DetailViewController *detailVC = [[DetailViewController alloc] init];
    detailVC.webUrl = model.gourl;
    detailVC.imagesrc = model.imgsrc;
    detailVC.title = model.title;
    detailVC.type = @"detail";
    [self.navigationController pushViewController:detailVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark --- 提醒视图 ---
//添加 收藏提醒框图
- (void)showAlertMessage:(NSString *)message {
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"通知" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    [self performSelector:@selector(dimissAlert:) withObject:alert afterDelay:1];
    
}

// 提醒视图消失
- (void)dimissAlert:(UIAlertView *)alert {
    
    if (alert) {
        [alert dismissWithClickedButtonIndex:[alert cancelButtonIndex] animated:YES];
    }
}






/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
